import re
import json
import logging

from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django import http
from .models import User

from utils.views import LoginRequiredJsonMixin
from celery_tasks.email.tasks import send_verify_email
from .utils import generate_verify_email_url, check_verify_email_token

logger = logging.getLogger('django')


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        if not all([username, password, password2, mobile, allow]):
            return http.HttpResponseForbidden('缺少必要参数')

        # if not re.match(r'[a-zA-Z0-9_-]{5, 20}$', username):
        #     return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        #
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseForbidden('请输入正确的手机号')
        #
        # if password != password2:
        #     return http.HttpResponseForbidden('两次输入的密码不一致')
        #
        # if not re.match(r'[0-9A-Za-z]{8, 20}$', password):
        #     return http.HttpResponseForbidden('请输入8-20位密码')

        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        login(request, user)
        response = redirect('/')
        response.set_cookie('username', user.username, max_age=3600*24*7)

        return response


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return redirect('users:login')
        if not re.match(r'[a-zA-Z0-9_-]{5,20}$', username):
            return redirect('users:login')
        if not re.match(r'[0-9A-Za-z]{8,20}$', password):
            return redirect('users:login')

        user = authenticate(username=username, password=password)
        if user is None:
            return redirect('users:login')

        login(request, user)
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect('/')
        response.set_cookie('username', user.username, max_age=3600*24*7)

        return response


class LogoutView(View):
    def get(self, request):
        response = redirect('/')
        response.delete_cookie('username')
        logout(request)
        return response


class UserInfoView(LoginRequiredMixin, View):
    # def get(self, request):
    #     if request.user.is_authenticated:
    #         return render(request, 'user_center_info.html')
    #     else:
    #         return redirect(reverse('users:login'))
    def get(self, request):
        user = request.user
        context = {
            'username': user.username,
            'mobile': user.mobile,
            'email': user.email,
            'email_active': user.email_active
        }
        return render(request, 'user_center_info.html', context)


class EmailView(LoginRequiredJsonMixin, View):
    def put(self, request):
        jdict = json.loads(request.body.decode())
        email = jdict.get('email')

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z0-9]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email错误')

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '添加邮箱失败'})

        verify_url = generate_verify_email_url(request.user)
        # send_verify_email.delay(email, verify_url)
        print(verify_url)

        return http.JsonResponse({'code': '0', 'errmsg': 'OK'})


class VerifyEmailView(View):
    def get(self, request):
        token = request.GET.get('token')

        if not token:
            return http.HttpResponseForbidden('缺少token')

        user = check_verify_email_token(token)
        if not user:
            return http.HttpResponseForbidden('无效的token')

        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('激活邮箱失败')

        return redirect(reverse('users:info'))
